package com.netcracker.studies;


import Bank.User;
import DBConnection.DBAPI;
import Beans.AuthorizationBean;
import Beans.AuthorizationBeanInterface;
import Bank.MD5Utils;
import DBConnection.DBObject;

import org.apache.log4j.Logger;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import java.util.Objects;

@WebServlet(name = "AuthorizationServlet")
public class AuthorizationServlet extends BaseServlet {
    private static final Logger log = Logger.getLogger(User.class);
    protected void handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain; charset=utf-8");
        try {
            HttpSession session = request.getSession(true);
//            if (request.getParameter("login").isEmpty()) {
//                response.getWriter().write("Введите данные для входа");
//                return;
//            }

            DBObject d1 = DBAPI.getUserByLogin(request.getParameter("login"));
            if (d1==null){
                response.getWriter().write("Такого логина не существует");
                return;
            }


            User user = DBAPI.getUser(d1);



            if (user != null) {

                if ((Objects.equals(request.getParameter("login"), user.getLogin())) && Objects.equals(MD5Utils.md5Custom(request.getParameter("password")), user.getPassword())) {
                    session.setAttribute("UserBean", new AuthorizationBean(user));
                    AuthorizationBeanInterface a = (AuthorizationBeanInterface) session.getAttribute("UserBean");
                    //response.getWriter().write(a.getMessage());
                    response.sendRedirect("index.jsp");

                } else
                {
                    response.getWriter().write("Неверно введен пароль");
                }

            }
            else
            {
                response.getWriter().write("Такого логина не существует");
            }
        } catch (Exception e) {
            response.getWriter().write("Такого логина не существует");
            e.printStackTrace();
            throw new ServletException(e.getMessage());
                  }
    }

    protected void handleGetRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //response.getWriter().write("autorization.jsp");
        request.getRequestDispatcher("autorization.jsp").forward(request,response);
    }
}
